#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define SERVER_PORT   8888          /*服务器端口号*/
#define Connect_Num   10            /*服务器最多主机连接数量*/

int main(void)
{
    struct sockaddr_in server_addr = {0};
    struct sockaddr_in client_addr = {0};
    int sockfd,connfd;
    int ret;
    char ip_str[20] = {0};
    char recvbuf[512];
    int Addrlen = sizeof(client_addr);

    /*1.创建socket套接字*/
    sockfd =  socket(AF_INET , SOCK_STREAM, 0);
    if(-1 == sockfd){
        perror("sock error");
        exit(EXIT_FAILURE);
    }

    /*2.将套接字与指定端口号绑定*/
    server_addr.sin_family = AF_INET;               /*IPV4*/
    server_addr.sin_port = htons(SERVER_PORT);      /*服务器端口号*/
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY); /*设置任意IP地址*/

    ret = bind(sockfd, (const struct sockaddr *)&server_addr,sizeof(server_addr));
    if(-1 == ret){
        perror("bind error");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    /*3.监听*/
    ret = listen(sockfd, Connect_Num);
    if(-1 == ret){
        perror("listen error");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    /*4.阻塞等待客户端连接*/
    connfd = accept(sockfd, (struct sockaddr *)&client_addr, &Addrlen);
    if(-1 == connfd){
        perror("accept error");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    printf("有客户端接入...\n");
    inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, ip_str, sizeof(ip_str));
    printf("客户端主机的 IP 地址: %s\n", ip_str);
    printf("客户端进程的端口号: %d\n", client_addr.sin_port);

    for(;;){

        /*接收缓冲区清空*/
        memset(recvbuf,0,sizeof(recvbuf));

        /*读数据*/
        ret = recv(connfd,recvbuf,sizeof(recvbuf),0);
        if(-1 == ret){
            perror("recv error");
            close(connfd);
            break;
        }

        /*打印*/
        printf("from client: %s\n",recvbuf);

        /*读取到"quit"则关闭套接字退出程序*/
        if(!strncmp("quit",recvbuf,4)){
            printf("server exit....\n");
            close(connfd);
            break;
        }
    }

    /*关闭套接字*/
    close(sockfd);
    exit(EXIT_SUCCESS);
}